# 贪吃蛇小游戏，基于pygame
# 主要游戏逻辑
import sys
# import random
import pygame
from random import randint
from pygame.locals import *


# 配置常量
FPS = 15
WINDOWWIDTH = 640
WINDOWHEIGHT = 480
CELLSIZE = 20
assert WINDOWWIDTH % CELLSIZE == 0 and WINDOWHEIGHT % CELLSIZE == 0, "画板宽度应该为小格子的整数倍"
CELLWIDTH = int(WINDOWWIDTH / CELLSIZE)     # 一列的格子数  32
CELLHEIGHT = int(WINDOWHEIGHT / CELLSIZE)   # 24

# RGB颜色 （255， 10， 12）
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
DARKGREEN = (0, 155, 0)
DARKGRAY = (40, 40, 40)
BGCOLOR = BLACK

UP = 'up'
DOWN = 'down'
LEFT = 'left'
RIGHT = 'right'

HEAD = 0

# 游戏窗口初始化
pygame.init()
FPSCLOCK = pygame.time.Clock()
DISPLAYSURF = pygame.display.set_mode(size=(WINDOWWIDTH, WINDOWHEIGHT))
BASICFONT = pygame.font.Font('arial.ttf', 18)
pygame.display.set_caption('贪吃蛇')

# 主逻辑
def show_start_screen():
    pass

def draw_grid():
    # 栅格线
    for x in range(0, WINDOWWIDTH, CELLSIZE):
        pygame.draw.line(DISPLAYSURF, DARKGRAY, (x, 0), (x, WINDOWHEIGHT))
    for y in range(0, WINDOWHEIGHT, CELLSIZE):
        pygame.draw.line(DISPLAYSURF, DARKGRAY, (0, y), (WINDOWWIDTH, y))

def draw_worm(wormbody):
    # 绘制虫子
    for cell in wormbody:
        x = cell['x'] * CELLSIZE
        y = cell['y'] * CELLSIZE
        worm_cell_rect = pygame.Rect(x, y, CELLSIZE, CELLSIZE)
        pygame.draw.rect(DISPLAYSURF, DARKGREEN, worm_cell_rect)

def draw_apple(apple):
    x = apple['x'] * CELLSIZE
    y = apple['y'] * CELLSIZE
    worm_cell_rect = pygame.Rect(x, y, CELLSIZE, CELLSIZE)
    pygame.draw.rect(DISPLAYSURF, RED, worm_cell_rect)

def run_game():
    """游戏主逻辑"""
    # 虫子的身体和初始位置
    startx = randint(5, CELLWIDTH - 5)
    starty = randint(5, CELLHEIGHT - 5)
    wormbody = [
        {'x': startx, 'y': starty},
        {'x': startx - 1, 'y': starty},
        {'x': startx - 2, 'y': starty},
    ]
    direction = RIGHT

    # 食物出现的位置
    apple = {'x': randint(0, CELLWIDTH-1), 'y': randint(0, CELLHEIGHT-1)}

    # 事件循环
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            # 检测键盘按键点击
            elif event.type == KEYDOWN:
                if event.key == K_LEFT and direction != RIGHT:
                    direction = LEFT
                elif event.key == K_RIGHT and direction != LEFT:
                    direction = RIGHT
                elif event.key == K_DOWN and direction != UP:
                    direction = DOWN
                elif event.key == K_UP and direction != DOWN:
                    direction = UP

        # 碰撞检测。超出画板边界，吃到自己身体
        if wormbody[0]['x'] == -1 or wormbody[0]['x'] == CELLWIDTH or \
            wormbody[0]['y'] == -1 or wormbody[0]['y'] == CELLHEIGHT:
            return None
        for cell in wormbody[1:]:
            if cell['x'] == wormbody[0]['x'] and cell['y'] == wormbody[0]['y']:
                return None

        # 检测和苹果碰撞。
        if wormbody[0]['x'] == apple['x'] and wormbody[0]['y'] == apple['y']:
            # 吃到苹果。先不用增加格子，跟后面逻辑有关系。再随机生成一个新食物。
            apple = {'x': randint(0, CELLWIDTH - 1), 'y': randint(0, CELLHEIGHT - 1)}
        else:
            # 没吃到苹果，体长不变，但因为后面逻辑会自动增长，所以这里抵消一下。
            del wormbody[-1]

        # 移动虫子。每次头部加1格，尾部减一个。
        if direction == UP:
            new_head = {'x': wormbody[0]['x'], 'y': wormbody[0]['y'] - 1}
        elif direction == DOWN:
            new_head = {'x': wormbody[0]['x'], 'y': wormbody[0]['y'] + 1}
        elif direction == LEFT:
            new_head = {'x': wormbody[0]['x'] - 1, 'y': wormbody[0]['y']}
        elif direction == RIGHT:
            new_head = {'x': wormbody[0]['x'] + 1, 'y': wormbody[0]['y']}
        wormbody.insert(0, new_head)

        # 把虫子、苹果、栅格、背景绘制出来
        DISPLAYSURF.fill(BGCOLOR)
        draw_grid()
        draw_worm(wormbody)
        draw_apple(apple)
        pygame.display.update()
        FPSCLOCK.tick(FPS)


def show_end_screen():
    pass


show_start_screen()
while True:
    run_game()
show_end_screen()